package org.eclipse.epsilon.emc.lom;


import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EStructuralFeature;

public class LiveObject {
	
	protected int id;
	protected String className;
	protected LiveObjectModel model;
	
	public LiveObject(int id, String className, LiveObjectModel model) {
		// TODO Auto-generated constructor stub
		this.id = id;
		this.className = className;
		this.model = model;
		
	}
	
	//TODO: Implement
	private Object cast(Object value, EClassifier type) {
		
		if (type.getInstanceClassName() == "java.lang.String"){
			return (String)value;
		}else if(type.getInstanceClassName() == "java.lang.Integer"){
			return (Integer)value;
		}else if(type.getInstanceClassName() == "java.lang.Double"){
			return (Double)value;
		}else{
			return null;
		}
	}
	
	//tha pexo me id
	public Object get(String property) {
		
		//model.getConnection();
		EClass eClass = model.classForName(className);
		
		System.err.println(eClass == null);
		
		EStructuralFeature sf = eClass.getEStructuralFeature(property);
		
		if (sf == null) return null;
		
		if (sf instanceof EAttribute) {
			
			
			if (sf.isMany()) {
				
				List<Object> castedValues = new ArrayList<Object>();
				Collection<String> values = model.getAttributeValues(id, property);
				
				for (String value : values) {
					castedValues.add(cast(value, sf.getEType()));
				}
				 
				return castedValues;
			}
			else {
				List<String> values = model.getAttributeValues(id, property);
				if (values.size() > 0) {
					return cast(values.get(0), sf.getEType());
					
				}
				else {
					return sf.getDefaultValue();
				}
			}
		}
		else {
			
			if(sf.isMany()){
				
				Collection<LiveObject> values = model.getLiveObject(id, property);
				
				//get the ids of the references at Reference table
				//ArrayList<Integer> ids = (ArrayList<Integer>) model.getReferenceId(id, property);
				
				//add LiveObjects to the Collection values
				//for (Integer id : ids) {
					//values.add(model.getLiveObjectById(id));
				//}
				
				return values;
			}
			else{
				Collection<LiveObject> values = model.getLiveObject(id, property);
				//ArrayList<Integer> ids = (ArrayList<Integer>) model.getReferenceId(id, property);
				
				if(values.size()>0){
					LiveObject x = model.getLiveObject(id, property).get(0);
					return x;
				
				}else{
					return sf.getDefaultValue();
				}
			}
				
				
			
			
		}
	}	
		
}

	
	

